package com.tedu.egweiboall.controller;


import com.tedu.egweiboall.mapper.UserMapper;
import com.tedu.egweiboall.pojo.dto.UserLoginDTO;
import com.tedu.egweiboall.pojo.dto.UserRegDTO;
import com.tedu.egweiboall.pojo.entity.User;
import com.tedu.egweiboall.pojo.vo.UserVO;
import com.tedu.egweiboall.result.JsonResult;
import com.tedu.egweiboall.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/v1/users/reg")
    @ApiOperation("用户注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        if (userMapper.selectByUsername(userRegDTO.getUsername())==null){
            User user = new User();
            BeanUtils.copyProperties(userRegDTO,user);
            user.setCreated(new Date());
            userMapper.insert(user);
            return new JsonResult(Status.OPERATION_SUCCESS);
        }
        return new JsonResult(Status.USER_EXIST);
    }

    @PostMapping("/v1/users/login")
    @ApiOperation("用户登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user==null){
            return new JsonResult(Status.USERNAME_ERROR);
        } else if (!user.getPassword().equals(userLoginDTO.getPassword())) {
            return new JsonResult(Status.PASSWORD_ERROR);
        }
        session.setAttribute("user",user);
        return new JsonResult(Status.OPERATION_SUCCESS);
    }

    @GetMapping("/v1/users/currentUser")
    @ApiOperation("获取当前登录用户信息")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return new JsonResult(Status.OPERATION_SUCCESS,userVO);
    }

    @GetMapping("/v1/users/logout")
    @ApiOperation("用户登出")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return new JsonResult(Status.OPERATION_SUCCESS);
    }

}
